'use client';

import React, { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { PageContainer } from '@ant-design/pro-components';
import { Spin } from 'antd';
import { DemandOrder } from '@/types/order';
import { orderApi } from '@/apis/order';
import { useMessage } from '@/hooks/useMessage';
import DemandOrderForm from '../components/DemandOrderForm';

interface DemandOrderPageProps {
  params: { id: string };
}

const DemandOrderPage: React.FC<DemandOrderPageProps> = ({ params }) => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode') || 'view'; // view | edit
  const [loading, setLoading] = useState(true);
  const [demandOrder, setDemandOrder] = useState<DemandOrder | null>(null);
  const message = useMessage();

  // 加载需求订单数据
  const loadDemandOrder = async () => {
    try {
      setLoading(true);
      // TODO: 调用真实API
      // const response = await orderApi.getDemandOrder(params.id);
      // setDemandOrder(response.data);
      
      // 模拟数据
      const mockData: DemandOrder = {
        id: params.id,
        orderNumber: 'D000001',
        userId: 'user001',
        user: {
          id: 'user001',
          username: 'zhangteacher',
          realName: '张老师',
          phone: '18812341234',
          email: 'zhang@example.com',
          role: 'level_3_user' as any,
          status: 'normal' as any,
          balance: 1500.00,
          isVerified: true,
          createdAt: '2025-01-01 00:00:00',
          updatedAt: '2025-03-28 10:30:00',
        },
        title: '材料表征综合测试需求',
        description: '需要对新型复合材料进行全面的物理化学性能表征，包括微观形貌观察、成分分析、力学性能测试等多项检测。',
        status: 'pending_review' as any,
        totalAmount: 2500.00,
        paymentMethod: 'team_balance' as any,
        instrumentOrders: [
          {
            id: 'inst001',
            instrumentId: 'instrument001',
            instrumentName: '扫描电子显微镜',
            instrumentCategory: '微观形貌与结构表征',
            amount: 800.00,
            status: 'pending_review' as any,
            responsiblePerson: {
              id: 'resp001',
              name: '李工程师',
              phone: '13912345678',
            },
          },
          {
            id: 'inst002',
            instrumentId: 'instrument002',
            instrumentName: 'X射线衍射仪',
            instrumentCategory: '成分与结构分析',
            amount: 600.00,
            status: 'pending_confirmation' as any,
            responsiblePerson: {
              id: 'resp002',
              name: '王工程师',
              phone: '13987654321',
            },
          },
          {
            id: 'inst003',
            instrumentId: 'instrument003',
            instrumentName: '万能试验机',
            instrumentCategory: '物理性能表征',
            amount: 1100.00,
            status: 'waiting_experiment' as any,
            responsiblePerson: {
              id: 'resp003',
              name: '赵工程师',
              phone: '13611111111',
            },
          },
        ],
        createdAt: '2025-03-28 10:30:00',
        updatedAt: '2025-03-28 15:20:00',
      };
      
      setDemandOrder(mockData);
    } catch (error) {
      console.error('加载需求订单失败:', error);
      message.error('加载需求订单失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (params.id && params.id !== 'create') {
      loadDemandOrder();
    }
  }, [params.id]);

  // 保存成功回调
  const handleSaveSuccess = (updatedOrder: DemandOrder) => {
    setDemandOrder(updatedOrder);
    message.success('保存成功');
    
    // 如果是编辑模式，跳转回查看模式
    if (mode === 'edit') {
      router.replace(`/orders/demand/${params.id}`);
    }
  };

  // 取消操作
  const handleCancel = () => {
    if (mode === 'edit') {
      // 编辑模式下返回查看模式
      router.replace(`/orders/demand/${params.id}`);
    } else {
      // 查看模式下返回列表
      router.push('/orders');
    }
  };

  if (loading) {
    return (
      <PageContainer>
        <div className="flex justify-center items-center h-64">
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  if (!demandOrder) {
    return (
      <PageContainer>
        <div className="text-center text-gray-500 py-16">
          需求订单不存在
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      title={mode === 'edit' ? '编辑需求订单' : '需求订单详情'}
    >
      <DemandOrderForm
        mode={mode as 'view' | 'edit'}
        initialData={demandOrder}
        onSave={handleSaveSuccess}
        onCancel={handleCancel}
        currentUserRole="admin"
        currentUserId="current_user"
      />
    </PageContainer>
  );
};

export default DemandOrderPage; 